package com.wlc.service.impl;

import com.wlc.mapper.DeptMapper;
import com.wlc.pojo.Dept;
import com.wlc.pojo.PageResult;
import com.wlc.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DeptServiceImpl implements DeptService {

    @Override
    public PageResult<Dept> findDeptList(String deptName, Integer status, Integer page, Integer size) {
        log.info("查询部门列表分页: deptName={}, status={}, page={}, size={}",
                deptName, status, page, size);

        if (page == null || page < 1) page = 1;
        if (size == null || size < 1) size = 10;

        Long total = deptMapper.selectDeptCount(deptName, status);
        List<Dept> depts = deptMapper.selectDeptList(deptName, status, (page - 1) * size, size);

        return new PageResult<>(total, depts);
    }

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public Dept findById(Long id) {
        log.info("根据ID查询部门: {}", id);
        return deptMapper.selectById(id);
    }

    @Override
    public List<Dept> findAll() {
        log.info("查询所有部门");
        return deptMapper.selectAll();
    }

    @Override
    public List<Dept> findTree() {
        log.info("查询部门树形结构");
        List<Dept> allDepts = deptMapper.selectTree();
        return buildDeptTree(allDepts, 0L);
    }

    /**
     * 构建部门树形结构
     */
    private List<Dept> buildDeptTree(List<Dept> depts, Long parentId) {
        return depts.stream()
                .filter(dept -> parentId.equals(dept.getParentId()))
                .peek(dept -> dept.setChildren(buildDeptTree(depts, dept.getId())))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void save(Dept dept) {
        log.info("新增部门: {}", dept.getDeptName());

        // 设置默认值
        dept.setStatus(1);
        // 移除 isDeleted 设置
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        if (dept.getParentId() == null) {
            dept.setParentId(0L);
        }

        int result = deptMapper.insert(dept);
        if (result <= 0) {
            throw new RuntimeException("新增部门失败");
        }
        log.info("新增部门成功: {}", dept.getDeptName());
    }

    @Override
    @Transactional
    public void update(Dept dept) {
        log.info("更新部门: {}", dept.getId());

        Dept existingDept = deptMapper.selectById(dept.getId());
        if (existingDept == null) {
            throw new RuntimeException("部门不存在");
        }

        // 防止设置自己为父部门
        if (dept.getId().equals(dept.getParentId())) {
            throw new RuntimeException("不能设置自己为父部门");
        }

        dept.setUpdateTime(LocalDateTime.now());
        int result = deptMapper.update(dept);
        if (result <= 0) {
            throw new RuntimeException("更新部门失败");
        }
        log.info("更新部门成功: {}", dept.getId());
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        log.info("删除部门: {}", id);

        Dept dept = deptMapper.selectById(id);
        if (dept == null) {
            throw new RuntimeException("部门不存在");
        }

        // 检查是否有子部门
        if (deptMapper.existsChildren(id)) {
            throw new RuntimeException("该部门下存在子部门，无法删除");
        }

        // 改为物理删除
        int result = deptMapper.deleteById(id);
        if (result <= 0) {
            throw new RuntimeException("删除部门失败");
        }
        log.info("删除部门成功: {}", id);
    }

    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        log.info("更新部门状态: id={}, status={}", id, status);

        Dept dept = deptMapper.selectById(id);
        if (dept == null) {
            throw new RuntimeException("部门不存在");
        }

        if (status != 0 && status != 1) {
            throw new RuntimeException("状态值不合法");
        }

        int result = deptMapper.updateStatus(id, status);
        if (result <= 0) {
            throw new RuntimeException("更新部门状态失败");
        }
        log.info("更新部门状态成功: id={}, status={}", id, status);
    }
}